package itheima.controller;

import itheima.pojo.Result;
import itheima.pojo.User;
import itheima.service.UserService;
import itheima.utils.JwtUtil;
import itheima.utils.Md5Util;
import itheima.utils.ThreadLocalUtil;
import jakarta.validation.constraints.Pattern;
import org.hibernate.validator.constraints.URL;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
@Validated
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 注册
     *
     * @param username
     * @param password
     * @return
     */
    @PostMapping("/register")
    public Result register(@Pattern(regexp = "^\\S{5,16}$") String username, @Pattern(regexp = "^\\S{5,16}$") String password) {
        //1.查询用户
        User user = userService.findByUsername(username);
        if (user != null) {
            //占用
            return Result.error("用户名已存在");
        } else {
            //没有占用
            //注册用户
            userService.register(username, password);
            return Result.success();
        }
    }


    /**
     * 登录
     *
     * @param username
     * @param password
     * @return
     */
    @PostMapping("/login")
    public Result login(@Pattern(regexp = "^\\S{5,16}$") String username, @Pattern(regexp = "^\\S{5,16}$") String password) {
        //1.查询用户
        User user = userService.findByUsername(username);
        //2.判断用户是否存在
        if (user == null) {
            return Result.error("用户名不存在");
        } else {
            //3.判断密码是否正确
            if (Md5Util.getMD5String(password).equals(user.getPassword())) {
                // 登录成功后，生成JWT令牌并返回
                // 创建一个存储用户信息的Map，用于放入JWT令牌中
                Map<String, Object> claims = new HashMap<>();
                // 将用户的ID放入Map
                claims.put("id", user.getId());
                // 将用户的用户名放入Map
                claims.put("username", user.getUsername());

                // 使用用户信息Map生成JWT令牌
                String token = JwtUtil.genToken(claims);

                // 将生成的JWT令牌c存到redis中
                stringRedisTemplate.opsForValue().set(token, token, 1, TimeUnit.HOURS);
                // 返回携带JWT令牌的成功结果
                return Result.success(token);

            }
            return Result.error("密码错误");
        }
    }



    /**
     * 获取用户信息
     * 通过解析授权令牌来获取用户信息
     *
     * @param token 授权令牌，用于解析用户信息
     * @return 返回一个结果对象，包含用户信息
     */
    @GetMapping("/userInfo")
    public Result<User> userInfo(@RequestHeader(name = "Authorization") String token){
        //根据用户名查询用户信息
//        Map<String, Object> map = JwtUtil.parseToken(token);
//        String username = (String) map.get("username");

        Map<String, Object> map = ThreadLocalUtil.get();
        String username = (String) map.get("username");
        User user = userService.findByUsername(username);
        return Result.success(user);
    }

    /**
     * 修改用户信息
     * @param user
     * @return
     */
    @PutMapping ("/update")
    public Result update(@RequestBody @Validated User user){
        userService.update(user);
        return Result.success();
    }

    /**
     * 修改头像
     * @param avatarUrl
     * @return
     */
    @PatchMapping("/updateAvatar")
    public Result updateAvatar(@RequestParam @URL String avatarUrl){
        userService.updateAvatar(avatarUrl);
        return Result.success();
    }

    /**
     * 修改密码
     * @param params
     * @param token
     * @return
     */
    @PatchMapping("/updatePwd")
    public Result updatePwd(@RequestBody Map<String,String> params,@RequestHeader("Authorization") String token){
        String oldPwd = params.get("old_pwd");
        String newPwd = params.get("new_pwd");
        String rePwd = params.get("re_pwd");

        if (!StringUtils.hasLength(oldPwd)||!StringUtils.hasLength(newPwd)||!StringUtils.hasLength(rePwd)){
            return Result.error("缺少关键参数");
        }

        //原密码是否正确
        //调用userService根据用户名拿到原密码,再和old-pwd比对
        Map<String, Object> map = ThreadLocalUtil.get();
        String username = (String) map.get("username");
        User user = userService.findByUsername(username);
        if (!Md5Util.getMD5String(oldPwd).equals(user.getPassword())){
            return Result.error("原密码错误");
        }

        if (!newPwd.equals(rePwd)){
            return Result.error("两次密码不一致");
        }
        //2.调用service完成密码更新
        userService.updatePwd(newPwd,username);

        //删除redis中的token
        stringRedisTemplate.opsForValue().getOperations().delete(token);
        return Result.success();
    }
}



































































